﻿(function () {

    window.crucible = window.crucible || {};
    var crucible = window.crucible;

    $(document).ready(function () {
        var view = new crucible.AssertionView();
    });

    crucible.AssertionView = function() {

    };

    crucible.AssertionView.prototype = function () {

        var integrateCommentData = function(node, commentData) {
            var children,
                comment,
                i,
                j;

            // commentData structure: [comment1, comment2, ...]
            // comment structure: { Id, Parent_Id, Body, Score }

            function childrenFilter(c) {
                return c.Parent_Id === comment.Id;
            }

            for (i = 0; i < commentData.length; i++) {

                if (!commentData[i].Parent_Id) {


                    comment = getById(node.Comments(), commentData[i].Id);

                    if (!comment) {
                        comment = new crucible.Comment(commentData[i]); // be sure to set comment so it gets picked up in the childrenFilter
                        node.Comments.push(comment); // Add this comment to the node's observable array
                    }

                    children = commentData.filter(childrenFilter);

                    for (j = 0; j < children.length; j++) {
                        var child = getById(comment.Replies(), children[j].Id);
                        if (!child) {
                            child = new crucible.Comment(children[j]);
                            comment.Replies.push(child);
                        }
                        child.parent = comment;
                    }
                }

            }

            node.Comments.sort(function(a, b) {
                return b.Score() - a.Score();
            });
        },
        loadNode = function (node) {
            var self = this;
            if (node.Published()) {
                //node.IsEditing(false);
                //if (node.original) {
                //    node.original.IsEditing(false);
                //}

                if (!node.hydrated) {
                    crucible.datacontext.hydrateNode(node);
                }
                
                node.Comments.removeAll();

                crucible.datacontext.loadComments(node, function (result) {
                    self.integrateCommentData(node, result);
                });
            }
        };

        function getById(array, id) {
            var i;
            for (i = 0; i < array.length; i++) {
                if (array[i].Id === id) {
                    return array[i];
                }
            }
            return null;
        }

        return {
            integrateCommentData: integrateCommentData,
            loadNode: loadNode
        };

    }();

}());